<?php
namespace models\service;
//use entities;

class AdministrationService {

	protected $ci;
	
	public function __construct() {
		$this -> ci = &get_instance();
	}

	public function findAllUser($indexAndCount) {
		return $this -> ci -> em -> getRepository('\models\entities\User') -> findAllAsObject();
	}

	public function findAllProfiles($indexAndCount) {
		return $this -> ci -> em -> getRepository('\models\entities\Profile') -> findAllAsObject();
	}
	
	public function saveUser($user, $userProfiles) {		
		if ($user != null) {			
			
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
				
				if(!preg_match("/^[a-zA-Z ]+$/",$user->getName())) {
					$this->ci->session->set_userdata('flash_message','Name can only consist of alphabetical and space.\nMinimum 2 characters and maximum 50.');
					return false;
				}
				if(!preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/",$user->getMail())) {
					$this->ci->session->set_userdata('flash_message','Please input valid email.');
					return false;
				}
				if(!preg_match("/^[a-zA-Z0-9_]{2,25}$/i",$user->getUserId())) {
					$this->ci->session->set_userdata('flash_message','The username can only consist of alphabetical, number and underscore.\nMinimum 6 characters and maximum 25.');
					return false;
				}
				if($user->getName() == "")
				{
					$this->ci->session->set_userdata('flash_message','Please fill the name.');
					return false;
				}
				if($user->getUserId() == "")
				{
					$this->ci->session->set_userdata('flash_message','Please fill the username.');
					return false;
				}
				if($user->getPassword() == "")
				{
					$this->ci->session->set_userdata('flash_message','Please fill the password.');
					return false;
				}
				if($user->getStatus() == "")
				{
					$this->ci->session->set_userdata('flash_message','Please select status of user.');
					return false;
				}
				if($user->getJabatan() == "")
				{
					$this->ci->session->set_userdata('flash_message','Please set jabatan.');
					return false;
				}
				else
				{
					$this->ci->em->persist($user);
					$this->ci->em->flush();	
					if ($userProfiles != NULL){
						
						if(count($userProfiles) == 0)
						{
							$this->ci->session->set_userdata('flash_message','Please set profile of user.');
							return false;
						}
						
						$criteria = array('userId' => $user->getUserId());
						$oldUserProfile = $this -> ci->em -> getRepository('\models\entities\UserProfile') -> findOneBy($criteria);
						if (count($oldUserProfile) > 0){
							// remove all user profile
							if ($this -> deleteUserProfilesByUser($oldUserProfile->getUserId()) === FALSE){
								throw new \Exception("GAGAL DELETE USERPROFILE");		
							}
						}
						
						foreach ($userProfiles as $userProfile) {						
							$userProfile->setUserId($user->getUserId());
							if ($this->insertUserProfiles($userProfile) === FALSE){
								throw new \Exception("GAGAL INSERT USERPROFILE");
							}	
						}			
								
					}
				}
				$this->ci->em->getConnection()->commit();						
				
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo "Exception ".$e->getMessage()." Exit";
				die();
			    //var_dump($e);
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function deleteUserProfilesByUser($user) {
		
		if ($user != "") {
			$criteria = array('userId' => $user);
			$item = $this -> ci -> em -> getRepository('\models\entities\UserProfile') -> findOneBy($criteria);
			$this -> ci -> em -> remove($item);
			$this -> ci -> em -> flush();

			return TRUE;
		}

		return FALSE;
	}
	
	public function insertUserProfiles($userProfile){
		try {
			$this->ci->em->persist($userProfile);
			$this->ci->em->flush();
			return TRUE;
		} catch (\Exception $e) {
			return FALSE;
		}
	}
	
	//START Provinsi
	public function findAllPropinsi() {
		return $this -> ci -> em -> getRepository('\models\entities\Propinsi') -> findAllAsObject();
	}
	
	public function savePropinsi($param) {		
		if ($param != null) {			
			
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {		
					if($param['Propinsi']['id']=='')
					{
					
						$criteria = array('nama' => $param['Propinsi']['nama']);
						$keywordPropinsies = $this->ci->em->getRepository('models\entities\Propinsi') -> findBy($criteria);
						if(count($keywordPropinsies) > 0)
						{
							// NAMA SUDAH ADA NOTIF
							return false;
						}
						else
						{											
							$propinsi = new \models\entities\Propinsi;
							$propinsi->setNama($param['Propinsi']['nama']);
							$this->ci->em->persist($propinsi);
							$this->ci->em->flush();

						}
					}
					else
					{
						$criteria = array('id' => $param['Propinsi']['id']);
						$keywordPropinsi = $this->ci->em->getRepository('models\entities\Propinsi') -> findOneBy($criteria);
						if ($keywordPropinsi->getNama() == $param['Propinsi']['nama']){
							// NAMA DAN ID SAMA NOTIF
							return false;
						} else {
							$keywordPropinsi -> setNama($param['Propinsi']['nama']);
							$this->ci->em->persist($keywordPropinsi);
							$this->ci->em->flush();
						}
					}	
						
				$this->ci->em->getConnection()->commit();						
				return true;
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo "Exception ".$e->getMessage()." Exit";
				die();
			    //var_dump($e);
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function saveDistrik($param) {		
		if ($param != null) {					
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
					if($param['Distrik']['id']=='')
					{
						$criteria = array('nama' => $param['Distrik']['nama']);
						$keywordDistriks = $this->ci->em->getRepository('models\entities\Distrik') -> findBy($criteria);
						if(count($keywordDistriks) > 0)
						{
							// NAMA SUDAH ADA NOTIF
							return false;
						}
						else
						{				
							$distrik = new \models\entities\Distrik;
							$distrik->setNama($param['Distrik']['nama']);
							$criteria = array('id' => $param['Distrik']['propinsi']);
							$objectPropinsi = $this->ci->em->getRepository('models\entities\Propinsi') -> findOneBy($criteria);
							$distrik->setPropinsi($objectPropinsi);
							$this->ci->em->persist($distrik);
							$this->ci->em->flush();
						}
					}
					else
					{
						$criteria = array('id' => $param['Distrik']['id']);
						$distrik = $this->ci->em->getRepository('models\entities\Distrik') -> findOneBy($criteria);						
						$distrik->setNama($param['Distrik']['nama']);
						$criteria = array('id' => $param['Distrik']['propinsi']);
						$objectPropinsi = $this->ci->em->getRepository('models\entities\Propinsi') -> findOneBy($criteria);	
						$distrik->setPropinsi($objectPropinsi);
						$this->ci->em->persist($distrik);
						$this->ci->em->flush();
					}	
						
				$this->ci->em->getConnection()->commit();						
				return true;
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo "Exception ".$e->getMessage()." Exit";
				die();
			    //var_dump($e);
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	//Change Password
	public function changePassword($param) {		
		if ($param != null) {					
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
					//Check User Yang Sedang Login Sama Atau Tidak Dengan Yang Akan Diganti Passwordnya
					if($param['User']['loggingIn'] == $param['User']['userId'])
					{
						//Check Old Password
						$criteria = array('userId' => $param['User']['userId']);
						$user = $this->ci->em->getRepository('models\entities\User') -> findOneBy($criteria);
						if($user->getPassword() == $param['User']['oldPassword'])
						{
							//Check New Password and Confirm Password
							if($param['User']['password'] == $param['User']['confirmPassword'])
							{
								$user -> setPassword($param['User']['password']);
								$this->ci->em->persist($user);
								$this->ci->em->flush();
							}
							else
							{

								//die('confirm password salah');
								$this->ci->session->set_userdata('flash_message','Konfirmasi password tidak cocok');
								return false;
							}
						}
						else
						{
							$this->ci->session->set_userdata('flash_message','Password lama salah');
							return false;
						}
					}
					else
					{
						$this->ci->session->set_userdata('flash_message','User login berbeda');
						return false;
					}
				$this->ci->em->getConnection()->commit();						
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo "Exception ".$e->getMessage()." Exit";
			    $this->ci->session->set_userdata('flash_message','Kesalahan : '.$e->getMessage());
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
